//
//  DR_SplitPDFVC.swift
//  DocReaderRP
//
//  Created by  mac on 2025/11/18.
//

import UIKit
import SnapKit
import Toast_Swift

class DR_SplitPDFVC: DR_BaseVC {
    
    private let pdfFileURL: URL
    private var pageImages: [UIImage] = []
    private var selectedPageIndices: Set<Int> = []
    
    init(pdfFileURL: URL) {
        self.pdfFileURL = pdfFileURL
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupConstraints()
        loadPDFPages()
    }
    
    private func setupUI() {
        view.backgroundColor = .white
        view.addSubview(backButton)
        view.addSubview(titleLabel)
        view.addSubview(selectAllButton)
        view.addSubview(collectionView)
        view.addSubview(splitButton)
        
        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        selectAllButton.addTarget(self, action: #selector(clickSelectAllButton), for: .touchUpInside)
        splitButton.addTarget(self, action: #selector(clickSplitButton), for: .touchUpInside)
        
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(DR_SplitPDFPageCell.self, forCellWithReuseIdentifier: DR_SplitPDFPageCell.identifier)
    }
    
    private func setupConstraints() {
        backButton.snp.makeConstraints { make in
            make.leading.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.width.equalTo(56)
            make.height.equalTo(44)
        }
        
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalTo(backButton)
        }
        
        selectAllButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.centerY.equalTo(backButton)
            make.height.equalTo(30)
        }
        
        collectionView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.top.equalTo(backButton.snp.bottom).offset(16)
            make.bottom.equalTo(splitButton.snp.top).offset(-16)
        }
        
        splitButton.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview().inset(20)
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-20)
            make.height.equalTo(50)
        }
    }
    
    private func loadPDFPages() {
        // 显示加载提示
        view.makeToastActivity(.center)
        
        // 在后台线程提取PDF页面
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            let images = DR_PDFTool.shared.extractPDFPagesAsImages(fileURL: self.pdfFileURL)
            
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                self.pageImages = images
                self.collectionView.reloadData()
                
                if images.isEmpty {
                    self.view.makeToast("pdf_extract".localized, duration: 2.0, position: .center)
                }
            }
        }
    }
    
    @objc private func clickBackButton() {
        navigationController?.popViewController(animated: true)
    }
    
    @objc private func clickSelectAllButton() {
        if selectedPageIndices.count == pageImages.count {
            // 全部已选中，取消全选
            selectedPageIndices.removeAll()
            selectAllButton.setTitle("sel_all".localized, for: .normal)
        } else {
            // 全选
            selectedPageIndices = Set(0..<pageImages.count)
            selectAllButton.setTitle("sel_all".localized, for: .normal)
        }
        collectionView.reloadData()
        updateSplitButton()
    }
    
    @objc private func clickSplitButton() {
        guard !selectedPageIndices.isEmpty else {
            view.makeToast("sel_page".localized, duration: 2.0, position: .center)
            return
        }
        
        // 显示输入文件名的弹窗
        showSplitNameInputSheet()
    }
    
    private func showSplitNameInputSheet() {
        let renameSheet = DR_RenameSheet()
        renameSheet.configure(with: "")
        
        renameSheet.onConfirm = { [weak self] fileName in
            guard let self = self else { return }
            guard !fileName.isEmpty else {
                self.view.makeToast("sel_named".localized, duration: 2.0, position: .center)
                return
            }
            
            // 执行分割
            self.performSplitPDF(fileName: fileName)
        }
        
        renameSheet.onCancel = {
            // 取消操作
        }
        
        // 显示弹窗
        if let window = UIApplication.shared.keyWindowCompat {
            renameSheet.show(in: window)
        } else if let tabBarController = self.tabBarController {
            renameSheet.show(in: tabBarController.view)
        } else {
            renameSheet.show(in: view)
        }
    }
    
    private func performSplitPDF(fileName: String) {
        // 显示加载提示
        view.makeToastActivity(.center)
        
        // 在后台线程创建新PDF
        DispatchQueue.global(qos: .userInitiated).async { [weak self] in
            guard let self = self else { return }
            let selectedIndices = Array(self.selectedPageIndices).sorted()
            let newPDF = DR_PDFTool.shared.createPDFFromSelectedPages(
                sourceFileURL: self.pdfFileURL,
                selectedPageIndices: selectedIndices,
                fileName: fileName
            )
            
            DispatchQueue.main.async {
                self.view.hideToastActivity()
                
                if let pdfModel = newPDF {
                    // 发送文件导入通知，刷新文件列表
                    NotificationCenter.default.post(name: NSNotification.Name("FileImported"), object: nil)
                    
                    // 跳转到结果页面
                    let resultVC = DR_ResultVC()
                    resultVC.configure(with: pdfModel, operationType: .split)
                    self.pushHidingTabBar(resultVC, animated: true)
                } else {
                    self.view.makeToast("pdf_splitFail".localized, duration: 2.0, position: .center)
                }
            }
        }
    }
    
    private func updateSplitButton() {
        let count = selectedPageIndices.count
        if count > 0 {
            splitButton.setTitle("Split (\(count))", for: .normal)
            splitButton.isEnabled = true
            splitButton.alpha = 1.0
        } else {
            splitButton.setTitle("Split", for: .normal)
            splitButton.isEnabled = false
            splitButton.alpha = 0.5
        }
    }
    
    private let backButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setImage("common_back".toImage, for: .normal)
        return button
    }()
    
    private let titleLabel: UILabel = {
        let label = UILabel()
        label.text = "home_split".localized
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    private let selectAllButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("sel_all".localized, for: .normal)
        button.setTitleColor("#333FFF".toColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16)
        return button
    }()
    
    private let collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 12
        layout.sectionInset = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
        
        let cv = UICollectionView(frame: .zero, collectionViewLayout: layout)
        cv.backgroundColor = .white
        cv.showsVerticalScrollIndicator = false
        return cv
    }()
    
    private let splitButton: UIButton = {
        let button = UIButton(type: .custom)
        button.setTitle("split_title".localized, for: .normal)
        button.setTitleColor(.white, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 16, weight: .medium)
        button.backgroundColor = "#333FFF".toColor
        button.layer.cornerRadius = 25
        button.isEnabled = false
        button.alpha = 0.5
        return button
    }()
}

// MARK: - UICollectionViewDataSource, UICollectionViewDelegate
extension DR_SplitPDFVC: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pageImages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: DR_SplitPDFPageCell.identifier, for: indexPath) as! DR_SplitPDFPageCell
        let image = pageImages[indexPath.item]
        let isSelected = selectedPageIndices.contains(indexPath.item)
        cell.configure(with: image, pageNumber: indexPath.item + 1, isSelected: isSelected)
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.item
        if selectedPageIndices.contains(index) {
            selectedPageIndices.remove(index)
        } else {
            selectedPageIndices.insert(index)
        }
        collectionView.reloadItems(at: [indexPath])
        updateSplitButton()
        
        // 更新全选按钮状态
        if selectedPageIndices.count == pageImages.count {
            selectAllButton.setTitle("sel_all".localized, for: .normal)
        } else {
            selectAllButton.setTitle("sel_all".localized, for: .normal)
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let spacing: CGFloat = 12
        let insets: CGFloat = 16 * 2
        let columns: CGFloat = 3
        let totalSpacing = spacing * (columns - 1) + insets
        let width = (collectionView.bounds.width - totalSpacing) / columns
        let height = width * 1.3 // 根据图片比例调整
        return CGSize(width: width, height: height)
    }
}

// MARK: - Split PDF Page Cell
class DR_SplitPDFPageCell: UICollectionViewCell {
    
    static let identifier = "DR_SplitPDFPageCell"
    
    private let imageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        imageView.backgroundColor = "#F6F7FF".toColor
        imageView.layer.cornerRadius = 8
        imageView.layer.masksToBounds = true
        return imageView
    }()
    
    private let pageNumberLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFont(ofSize: 12, weight: .medium)
        label.textColor = .black
        label.textAlignment = .center
        return label
    }()
    
    private let checkmarkView: UIView = {
        let view = UIView()
        view.backgroundColor = "#333FFF".toColor
        view.layer.cornerRadius = 12
        view.isHidden = true
        return view
    }()
    
    private let checkmarkImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.image = UIImage(systemName: "checkmark")
        imageView.tintColor = .white
        imageView.contentMode = .scaleAspectFit
        return imageView
    }()
    
    private let overlayView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
        view.layer.cornerRadius = 8
        view.isHidden = true
        return view
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        setupConstraints()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(pageNumberLabel)
        contentView.addSubview(overlayView)
        contentView.addSubview(checkmarkView)
        checkmarkView.addSubview(checkmarkImageView)
    }
    
    private func setupConstraints() {
        imageView.snp.makeConstraints { make in
            make.top.leading.trailing.equalToSuperview()
            make.height.equalTo(imageView.snp.width).multipliedBy(1.3)
        }
        
        pageNumberLabel.snp.makeConstraints { make in
            make.top.equalTo(imageView.snp.bottom).offset(4)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        
        overlayView.snp.makeConstraints { make in
            make.edges.equalTo(imageView)
        }
        
        checkmarkView.snp.makeConstraints { make in
            make.trailing.equalTo(imageView).offset(-8)
            make.top.equalTo(imageView).offset(8)
            make.width.height.equalTo(24)
        }
        
        checkmarkImageView.snp.makeConstraints { make in
            make.center.equalToSuperview()
            make.width.height.equalTo(14)
        }
    }
    
    func configure(with image: UIImage, pageNumber: Int, isSelected: Bool) {
        imageView.image = image
        pageNumberLabel.text = "Page \(pageNumber)"
        checkmarkView.isHidden = !isSelected
        overlayView.isHidden = !isSelected
    }
}

